package com.jeecg.demo.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.google.gson.Gson;
import com.jeecg.demo.entity.SysOrderVerifyEntity;
import com.jeecg.demo.entity.TraderEntity;
import com.jeecg.demo.entity.TraderattrEntity;
import com.jeecg.demo.service.SysOrderVerifyServiceI;
import com.jeecg.demo.service.SysUserServiceI;
import com.jeecg.demo.service.TraderServiceI;
import com.jeecg.demo.service.TraderattrServiceI;
import com.jeecg.demo.util.PopupDataBindUtil;
import org.apache.commons.lang3.StringUtils;
import org.jeecgframework.core.common.controller.BaseController;
import org.jeecgframework.core.common.exception.BusinessException;
import org.jeecgframework.core.common.hibernate.qbc.CriteriaQuery;
import org.jeecgframework.core.common.model.json.AjaxJson;
import org.jeecgframework.core.common.model.json.DataGrid;
import org.jeecgframework.core.constant.Globals;
import org.jeecgframework.core.util.MyBeanUtils;
import org.jeecgframework.core.util.ResourceUtil;
import org.jeecgframework.core.util.StringUtil;
import org.jeecgframework.poi.excel.ExcelImportUtil;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.jeecgframework.poi.excel.entity.ImportParams;
import org.jeecgframework.poi.excel.entity.vo.NormalExcelConstants;
import org.jeecgframework.tag.core.easyui.TagUtil;
import org.jeecgframework.web.system.pojo.base.TSType;
import org.jeecgframework.web.system.pojo.base.TSTypegroup;
import org.jeecgframework.web.system.pojo.base.TSUser;
import org.jeecgframework.web.system.service.SystemService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @Title: Controller
 * @Description: TRADER
 * @author onlineGenerator
 * @date 2018-11-15 08:58:56
 * @version V1.0
 *
 */
@Controller
@RequestMapping("/traderController")
public class TraderController extends BaseController {
    private static final Logger logger = LoggerFactory.getLogger(TraderController.class);

    @Autowired
    private TraderServiceI traderService;
    @Autowired
    private SystemService systemService;
    @Autowired
    private SysOrderVerifyServiceI sysOrderVerifyService;
    @Autowired
    private PopupDataBindUtil bindUtil;
    @Autowired
    private TraderattrServiceI traderAttrService;
    @Autowired
    private SysUserServiceI sysUserService;


    /**
     * TRADER列表 页面跳转
     *
     * @return
     */
    @RequestMapping(params = "list")
    public ModelAndView list(HttpServletRequest request, String type) {

        if ("info".equals(type)) {
            request.setAttribute("title", "交易商信息");
        }
        else if ("verify".equals(type)) {
            request.setAttribute("title", "交易商审核");
        }
        else if ("pwdreset".equals(type)) {
            request.setAttribute("title", "交易商资金密码重置");
        }

        request.setAttribute("type", type);

        return new ModelAndView("com/jeecg/trader/traderList");
    }

    /**
     * easyui AJAX请求数据
     *
     * @param request
     * @param response
     * @param dataGrid
     * @throws Exception
     */
    @RequestMapping(params = "datagrid")
    public void datagrid(TraderEntity trader, HttpServletRequest request, HttpServletResponse response, DataGrid dataGrid, String type) throws Exception {
        CriteriaQuery cq = new CriteriaQuery(TraderEntity.class, dataGrid);
        // 查询条件组装器
        // 如果绑定报表数据，则更新排序格式，将新增的虚拟列改为原表中对应列
        dataGrid.setSort(dataGrid.getSort().replace("regioncodeDicName", "regioncode"));
        org.jeecgframework.core.extend.hqlsearch.HqlGenerateUtil.installHql(cq, trader, request.getParameterMap());
        try {
            // 自定义追加查询条件
            if ("verify".equals(type)) {
                cq.eq("traderauthstatus", "2");

            }
        }
        catch (Exception e) {
            throw new BusinessException(e.getMessage());
        }
        // GetUserTenantId getuserfun=new GetUserTenantId();
        // String idString =
        // String.valueOf(systemService.findOneForJdbc(getuserfun.getSql(),getuserfun.getOrgcode()).get("worktypeid"));
        // int worktypeid = Integer.parseInt(idString);
        // cq.eq("worktypeid", worktypeid);
        cq.add();
        this.traderService.getDataGridReturn(cq, true);

        // 绑定报表数据
        bindUtil.BindReportFieldNameDataGrid(TraderEntity.class, dataGrid, "regioncode", "fullname");

        TagUtil.datagrid(response, dataGrid);
    }

    @RequestMapping(params = "doTradePwdreset")
    @ResponseBody
    public AjaxJson doTradePwdreset(TraderEntity trader,
            HttpServletRequest request) {
        String message = null;
        AjaxJson j = new AjaxJson();
        message = "交易资金密码重置成功";
        TraderEntity t = systemService.get(TraderEntity.class, trader.getId());
        try {
            t.setMoneypsd("111111");
            systemService.saveOrUpdate(t);
            systemService.addLog(message, Globals.Log_Type_UPDATE, Globals.Log_Leavel_INFO);
        }
        catch (Exception e) {
            e.printStackTrace();
            message = "交易资金密码重置失败";
            throw new BusinessException(e.getMessage());
        }
        j.setMsg(message);
        return j;
    }

    /**
     * 删除TRADER
     *
     * @return
     */
    @RequestMapping(params = "doDel")
    @ResponseBody
    public AjaxJson doDel(TraderEntity trader, HttpServletRequest request) {
        String message = null;
        AjaxJson j = new AjaxJson();
        trader = systemService.getEntity(TraderEntity.class, trader.getId());
        message = "删除成功";
        try {
            traderService.delete(trader);
            systemService.addLog(message, Globals.Log_Type_DEL,
                    Globals.Log_Leavel_INFO);
        }
        catch (Exception e) {
            e.printStackTrace();
            message = "删除失败";
            throw new BusinessException(e.getMessage());
        }
        j.setMsg(message);
        return j;
    }

    /**
     * 批量删除TRADER
     *
     * @return
     */
    @RequestMapping(params = "doBatchDel")
    @ResponseBody
    public AjaxJson doBatchDel(String ids, HttpServletRequest request) {

        String message = null;
        AjaxJson j = new AjaxJson();
        message = "删除成功";
        try {
            for (String id : ids.split(",")) {
                TraderEntity trader = systemService.getEntity(
                        TraderEntity.class, Integer.parseInt(id));
                traderService.delete(trader);
                systemService.addLog(message, Globals.Log_Type_DEL,
                        Globals.Log_Leavel_INFO);
            }
        }
        catch (Exception e) {
            e.printStackTrace();
            message = "删除失败";
            throw new BusinessException(e.getMessage());
        }
        j.setMsg(message);
        return j;
    }

    /**
     * 添加TRADER
     *
     * @return
     */
    @RequestMapping(params = "doAdd")
    @ResponseBody
    public AjaxJson doAdd(TraderEntity trader, HttpServletRequest request) {
        String message = null;
        AjaxJson j = new AjaxJson();
        message = "添加成功";
        try {
            traderService.save(trader);
            systemService.addLog(message, Globals.Log_Type_INSERT, Globals.Log_Leavel_INFO);
        }
        catch (Exception e) {
            e.printStackTrace();
            message = "添加失败";
            throw new BusinessException(e.getMessage());
        }
        j.setMsg(message);
        return j;
    }

    /**
     * 更新TRADER
     *
     * @return
     */
    @RequestMapping(params = "doUpdate")
    @ResponseBody
    public AjaxJson doUpdate(TraderEntity trader, HttpServletRequest request) {
        String message = null;
        AjaxJson j = new AjaxJson();
        message = "更新成功";
        TraderEntity t = traderService.get(TraderEntity.class, trader.getId());
        try {
            MyBeanUtils.copyBeanNotNull2Bean(trader, t);
            traderService.saveOrUpdate(t);
            systemService.addLog(message, Globals.Log_Type_UPDATE, Globals.Log_Leavel_INFO);
        }
        catch (Exception e) {
            e.printStackTrace();
            message = "更新失败";
            throw new BusinessException(e.getMessage());
        }
        j.setMsg(message);
        return j;
    }

    /**
     * 审核TRADER
     *
     * @return
     */
    @RequestMapping(params = "doVerify")
    @ResponseBody
    public AjaxJson doVerify(TraderEntity trader, HttpServletRequest request, String verifyflag, String verifynote) {
        String message = null;
        AjaxJson j = new AjaxJson();
        TraderEntity t = traderService.get(TraderEntity.class, trader.getId());
        TSUser u = ResourceUtil.getSessionUser();
        String beforestatus = "";

        try {
            // 根据认证申请状态判断审核前状态
            if (t.getTraderauthstatus().equals("1") || t.getTraderauthstatus().equals("2")) {
                beforestatus = "1";
            }
            else if (t.getTraderauthstatus().equals("3")) {
                beforestatus = "2";
            }
            else if (t.getTraderauthstatus().equals("4")) {
                beforestatus = "3";
            }

            // 设置审核记录
            SysOrderVerifyEntity verify = new SysOrderVerifyEntity();
            verify.setOrdid(trader.getId());
            verify.setOrdtype("TRADER_SP");
            verify.setBeforestatus(beforestatus);
            verify.setVerifyuserid(0);
            verify.setVerifynote(verifynote);
            verify.setVerifytime(new Date());
            verify.setOrderid(1);

            if ("true".equals(verifyflag)) {
                message = "审核成功";
                if (null != verifynote && !verifynote.equals("")) {
                    message += "\r\n审核意见:" + verifynote;
                }

                // 保存审核记录
                verify.setVerifystatus("2");
                sysOrderVerifyService.save(verify);

                // 保存状态
                Integer traderid = t.getTraderid();
                String str = String.valueOf(traderid).substring(2);
                Integer num = 814;
                if ("99999".equals(str)) {
                    num += 1;
                }
                String tradecode = num + str;
                t.setTradecode(tradecode);
                t.setTraderauthstatus("3");
                t.setTradertypeid("2");// 修改可交易状态 190318 suncp
                traderService.saveOrUpdate(t);
                getSynchronousResults(t);
                systemService.addLog(message, Globals.Log_Type_OTHER, Globals.Log_Leavel_INFO);

                /*水运用户同步 + 运销交易商同步*/
                Map<String,Object> maps = new HashMap();
                Map<String,Object> mapies = new HashMap<>();
                ArrayList list = new ArrayList();
                ArrayList lists = new ArrayList();
                String sql = " SELECT\n" +
                        "\ttr.FULLNAME AS \"companyName\",\n" +
                        "\tsys.LOGINNAME AS \"userName\",\n" +
                        "\tsys.PASSWORD AS \"password\",\n" +
                        "\tsys.MOBILE AS \"phone\" \n" +
                        "FROM\n" +
                        "\tSYS_USER sys\n" +
                        "LEFT JOIN\n" +
                        "\tTRADER tr \n" +
                        "ON \n" +
                        "\tsys.ORGID = tr.TRADERID \n" +
                        "WHERE\n" +
                        "\tsys.ORGID = ? ";

                /*公路用户同步*/
                String sqls = " SELECT\n" +
                        "\ttr.FULLNAME AS \"companyName\",\n" +
                        "\tsys.LOGINNAME AS \"userName\",\n" +
                        "\tsys.PASSWORD AS \"password\"\n" +
                        "FROM\n" +
                        "\tSYS_USER sys\n" +
                        "LEFT JOIN\n" +
                        "\tTRADER tr \n" +
                        "ON \n" +
                        "\tsys.ORGID = tr.TRADERID \n" +
                        "WHERE\n" +
                        "\tsys.ORGID = ? ";
                /*水运用户同步 + 运销交易商同步*/
                List<Map<String, Object>> listMap = systemService.findForJdbc(sql, t.getTraderid());

                /*公路用户同步*/
                List<Map<String, Object>> listMaps = systemService.findForJdbc(sqls, t.getTraderid());

                /*水运用户同步 + 运销交易商同步*/
                for (Map<String, Object> map : listMap) {
                    list.add(map);
                }

                /*公路用户同步*/
                for (Map<String, Object> mapes : listMaps) {
                    lists.add(mapes);
                }

                /*水运用户同步 + 运销交易商同步*/
                maps.put("userInfos",list);
                maps.put("isAll", "Y");
                maps.put("isEdit", "N");

                /*公路用户同步*/
                mapies.put("userInfos",lists);
                mapies.put("sysToken","wl20230110333222");

                /*水运用户同步 + 运销交易商同步*/
                String s = new Gson().toJson(maps);

                /*公路用户同步*/
                String ss = new Gson().toJson(mapies);
                System.out.println(s.toString());
                System.out.println("_________________________________________________________________________________________");
                System.out.println(ss.toString());

                RestTemplate template = new RestTemplate();
                LinkedMultiValueMap params = new LinkedMultiValueMap();
                String jsmt = new Gson().toJson(t);
                params.add("json", jsmt.toString());
                HttpHeaders headers = new HttpHeaders();
                HttpHeaders headeres = new HttpHeaders();
                MediaType type = MediaType.parseMediaType("application/x-www-form-urlencoded; charset=UTF-8");
                MediaType types = MediaType.parseMediaType("application/json; charset=UTF-8");


                headers.setContentType(type);
                headeres.setContentType(types);

                HttpEntity<LinkedMultiValueMap> req = new HttpEntity(params, headers);
                HttpEntity<LinkedMultiValueMap> reqs = new HttpEntity(s, headers);

                HttpEntity<LinkedMultiValueMap> reqes = new HttpEntity(ss, headeres);
                String ret = template.postForObject("http://192.168.0.241:8088/jeecg-boot/api/contront/saveTrader", req, String.class, new Object[0]);
                String rets = template.postForObject("https://gateway.hncldc.com/golder/api/alterSynchronizationUser", reqs, String.class);
                String retes = template.postForObject("https://dp-api.hncldc.com/api/v1/open-api/alterSynchronizationUser", reqes, String.class);
                System.out.println("---------------------开始同步用户---------------------");
                System.out.println("交易商同步:\t"+ret+"\n\n"+"水运用户同步:\t"+rets+"\n\n"+"公路用户同步:\t"+retes);
            }
            else if ("false".equals(verifyflag)) {
                message = "审核退回";
                if (null != verifynote && !verifynote.equals("")) {
                    message += "\r\n退回原因:" + verifynote;
                }

                // 保存审核记录
                verify.setVerifystatus("3");
                sysOrderVerifyService.save(verify);

                // 保存状态
                t.setTraderauthstatus("4");
                traderService.saveOrUpdate(t);

                systemService.addLog(message, Globals.Log_Type_OTHER, Globals.Log_Leavel_INFO);
            }
        }
        catch (Exception e) {
            e.printStackTrace();
            message = "审核失败";
            throw new BusinessException(e.getMessage());
        }
        j.setMsg(message);
        return j;
    }

    /**
     * TRADER新增页面跳转
     *
     * @return
     * @throws Exception
     */
    @RequestMapping(params = "goAdd")
    public ModelAndView goAdd(TraderEntity trader, HttpServletRequest req) throws Exception {
        List<TraderattrEntity> listTraderAttr = null;
        if (StringUtil.isNotEmpty(trader.getId())) {
            trader = traderService.getEntity(TraderEntity.class, trader.getId());
            req.setAttribute("traderPage", trader);

            String regionCode = trader.getRegioncode();
            if (regionCode != null && !regionCode.equals("")) {
                if (!regionCode.equals("01710000") && !regionCode.equals("01820000") && !regionCode.equals("01810000")) {
                    regionCode = regionCode.substring(0, 2) + "100000";
                }
            }

        }
        listTraderAttr = traderAttrService.findHql("from TraderattrEntity where regioncode = ?", "01100000");
        req.setAttribute("listAttr", listTraderAttr);
        return new ModelAndView("com/jeecg/trader/trader-add");
    }

    /**
     * TRADER编辑页面跳转
     *
     * @return
     * @throws Exception
     */
    @RequestMapping(params = "goUpdate")
    public ModelAndView goUpdate(TraderEntity trader, HttpServletRequest req)
            throws Exception {
        List<TraderattrEntity> listTraderAttr = null;
        if (StringUtil.isNotEmpty(trader.getId())) {
            trader = traderService.getEntity(TraderEntity.class, trader.getId());
            req.setAttribute("action", "traderController.do?doUpdate");
            req.setAttribute("traderPage", bindUtil.BindReportFieldName(TraderEntity.class, trader, "regioncode", "regionname"));
            String regionCode = trader.getRegioncode();
            if (regionCode != null && !regionCode.equals("")) {
                if (!regionCode.equals("01710000") && !regionCode.equals("01820000") && !regionCode.equals("01810000")) {
                    regionCode = regionCode.substring(0, 2) + "100000";
                }
            }
            listTraderAttr = traderAttrService.findHql("from TraderattrEntity where regioncode = ?", regionCode);
        }
        req.setAttribute("listAttr", listTraderAttr);
        return new ModelAndView("com/jeecg/trader/trader-update");
    }

    /**
     * TRADER审核页面跳转
     *
     * @return
     * @throws Exception
     */
    @RequestMapping(params = "goVerify")
    public ModelAndView goVerify(TraderEntity trader, HttpServletRequest req)
            throws Exception {
        List<TraderattrEntity> listTraderAttr = null;
        if (StringUtil.isNotEmpty(trader.getId())) {
            trader = traderService
                    .getEntity(TraderEntity.class, trader.getId());
            req.setAttribute("action", "traderController.do?doVerify");
            req.setAttribute("traderPage", bindUtil.BindReportFieldName(
                    TraderEntity.class, trader, "regioncode", "regionname"));
            String regionCode = trader.getRegioncode();
            if (regionCode != null && !regionCode.equals("")) {
                if (!regionCode.equals("01710000")
                        && !regionCode.equals("01820000")
                        && !regionCode.equals("01810000")) {
                    regionCode = regionCode.substring(0, 2) + "100000";
                }
            }
            listTraderAttr = traderAttrService.findHql(
                    "from TraderattrEntity where regioncode = ?", regionCode);
        }

        req.setAttribute("listAttr", listTraderAttr);

        return new ModelAndView("com/jeecg/trader/trader-update");
    }

    @RequestMapping(params = "goPwdreset")
    public ModelAndView goPwdreset(TraderEntity trader, HttpServletRequest req)
            throws Exception {
        if (StringUtil.isNotEmpty(trader.getId())) {
            trader = systemService
                    .getEntity(TraderEntity.class, trader.getId());
            req.setAttribute("action", "traderController.do?doTradePwdreset");
            req.setAttribute("traderPage", bindUtil.BindReportFieldName(
                    TraderEntity.class, trader, "regioncode", "regionname"));
        }
        return new ModelAndView("com/jeecg/trader/trader-update");
    }

    /**
     * 导入功能跳转
     *
     * @return
     */
    @RequestMapping(params = "upload")
    public ModelAndView upload(HttpServletRequest req) {
        req.setAttribute("controller_name", "traderController");
        return new ModelAndView("common/upload/pub_excel_upload");
    }

    /**
     * 导出excel
     *
     * @param request
     * @param response
     */
    @RequestMapping(params = "exportXls")
    public String exportXls(TraderEntity trader, HttpServletRequest request,HttpServletResponse response, DataGrid dataGrid, ModelMap modelMap,String ids) {
        CriteriaQuery cq = new CriteriaQuery(TraderEntity.class, dataGrid);
        org.jeecgframework.core.extend.hqlsearch.HqlGenerateUtil.installHql(cq,trader, request.getParameterMap());
        cq.in("id", bindUtil.idsToIntegerArray(ids));
        cq.add();
        List<TraderEntity> traders = this.traderService.getListByCriteriaQuery(cq, false);
        modelMap.put(NormalExcelConstants.FILE_NAME, "交易商信息");
        modelMap.put(NormalExcelConstants.CLASS, TraderEntity.class);
        modelMap.put(NormalExcelConstants.PARAMS, new ExportParams("交易商信息", "导出人:" + ResourceUtil.getSessionUser().getRealName(), "导出信息"));
        modelMap.put(NormalExcelConstants.DATA_LIST, traders);
        return NormalExcelConstants.JEECG_EXCEL_VIEW;
    }

    /**
     * 导出excel 使模板
     *
     * @param request
     * @param response
     */
    @RequestMapping(params = "exportXlsByT")
    public String exportXlsByT(TraderEntity trader, HttpServletRequest request, HttpServletResponse response, DataGrid dataGrid, ModelMap modelMap) {
        modelMap.put(NormalExcelConstants.FILE_NAME, "TRADER");
        modelMap.put(NormalExcelConstants.CLASS, TraderEntity.class);
        modelMap.put(NormalExcelConstants.PARAMS, new ExportParams("TRADER列表", "导出人:" + ResourceUtil.getSessionUser().getRealName(), "导出信息"));
        modelMap.put(NormalExcelConstants.DATA_LIST, new ArrayList());
        return NormalExcelConstants.JEECG_EXCEL_VIEW;
    }

    @SuppressWarnings("unchecked")
    @RequestMapping(params = "importExcel", method = RequestMethod.POST)
    @ResponseBody
    public AjaxJson importExcel(HttpServletRequest request,
            HttpServletResponse response) {
        AjaxJson j = new AjaxJson();

        String ace = null;
        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
        Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
        for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {
            MultipartFile file = entity.getValue();// 获取上传文件对象
            ImportParams params = new ImportParams();
            params.setTitleRows(2);
            params.setHeadRows(1);
            params.setNeedSave(true);
            try {
                List<TraderEntity> listTraderEntitys = ExcelImportUtil.importExcel(file.getInputStream(), TraderEntity.class, params);
                for (TraderEntity trader : listTraderEntitys) {
                    String sql = " SELECT tr.FULLNAME FROM TRADER tr WHERE tr.FULLNAME = ? ";
                    List<Map<String, Object>> listMap = systemService.findForJdbc(sql, trader.getFullname());
                    if (listMap.size() == 0) {
                        trader.setTradertypeid("2");
                        trader.setAddtime(new Date());
                        trader.setTraderauthstatus("3");
                        trader.setRegioncode("01430000");
                        traderService.save(trader);
                        j.setMsg("文件导入成功！");
                    }else {
                        j.setMsg("文件导入成功");

                    }
                }
            }
            catch (Exception e) {
                j.setMsg("文件导入失败！");
                logger.error(e.getMessage());
            }
            finally {
                try {
                    file.getInputStream().close();
                }
                catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return j;
    }

    /**
     * 更新TRADER
     *
     * @return
     */
    @RequestMapping(params = "doSynchronous")
    @ResponseBody
    public String doSynchronous(TraderEntity trader, HttpServletRequest request) {
        return getSynchronousResults(trader);
    }

    public String getSynchronousResults(TraderEntity trader) {
        String message = "同步失败";
        try {
            Map<String, Object> opMap = new HashMap();
            Integer traderid = trader.getTraderid();
            if (null != traderid) {
                TraderEntity entity = systemService.getEntity(
                        TraderEntity.class, trader.getTraderid());
                String firmId = entity.getTradecode();
                if (StringUtils.isNotEmpty(firmId)) {
                    String status = entity.getTraderauthstatus();
                    if ("3".equals(status)) {

                        String registerDateStr = "";
                        Date registerDate = entity.getAddtime();
                        if (null != registerDate) {
                            SimpleDateFormat df = new SimpleDateFormat(
                                    "yyyy-MM-dd HH:mm:ss");// 定义格式，不显示毫秒
                            registerDateStr = df.format(registerDate);
                        }
                        String name = entity.getFullname();
                        String firmType = entity.getIndustryid();

                        String creditNumber = entity.getCreditnumber();
                        String buslicCode = entity.getBusliccode();
                        String taxregCode = entity.getTaxregcode();

                        String contact = entity.getContacts();
                        String contactphone = entity.getOfficephone();
                        String phone = entity.getMobilephone();
                        String contactaddr = entity.getAddress();
                        String businessname = entity.getLegallyar();
                        String fundacc = entity.getBankaccountno();

                        opMap.put("firmId", firmId);
                        String statusName = getName("TRADERAUTHSTATUS", status);
                        opMap.put("status", urlEncode(statusName));
                        opMap.put("registerDate", registerDateStr);
                        opMap.put("name", urlEncode(name));
                        String firmTypeName = getName("HANGY", firmType);
                        opMap.put("firmType", urlEncode(firmTypeName));

                        List<Map<String, Object>> cardInfoList = new ArrayList();
                        Map<String, Object> creditNumberMap = new HashMap();
                        Map<String, Object> buslicCodeMap = new HashMap();
                        Map<String, Object> taxregCodeMap = new HashMap();
                        creditNumberMap.put("cardType", "1");
                        creditNumberMap.put("cardCode", creditNumber);
                        buslicCodeMap.put("cardType", "9");
                        buslicCodeMap.put("cardCode", buslicCode);
                        taxregCodeMap.put("cardType", "11");
                        taxregCodeMap.put("cardCode", taxregCode);
                        cardInfoList.add(creditNumberMap);
                        cardInfoList.add(buslicCodeMap);
                        cardInfoList.add(taxregCodeMap);

                        opMap.put("cardInfo", cardInfoList);
                        opMap.put("contact", urlEncode(contact));
                        opMap.put("contactphone", contactphone);
                        opMap.put("phone", phone);
                        opMap.put("contactaddr", urlEncode(contactaddr));
                        opMap.put("businessname", urlEncode(businessname));
                        opMap.put("fundacc", fundacc);
                        String outputStr = JSON.toJSONString(opMap);
                        String result = traderService.doSynchronous(outputStr);
                        if (StringUtils.isNotEmpty(result)) {
                            JSONObject parse = (JSONObject) JSON.parse(result);
                            String flag = parse.get("responsecode").toString();
                            if (flag.length() > 5) {
                                message = "同步成功";
                            }
                        }
                    }
                    else {
                        message = "未认证成功，请重新认证！";
                    }
                }
                else {
                    message = "企业编码不能为空！";
                }
            }
        }
        catch (Exception e) {
            e.printStackTrace();
            message = "同步失败";
            throw new BusinessException(e.getMessage());
        }
        return message;
    }

    public static String urlEncode(String rawValue) {
        String value = (rawValue == null) ? "" : rawValue;
        String encoded = null;

        try {
            encoded = URLEncoder.encode(value, "UTF-8").replace("+", "%20").replace("*", "%2A").replace("%7E", "~");
        }
        catch (UnsupportedEncodingException e) {
            System.err.println("Unknown encoding: " + "UTF-8");
        }

        return encoded;
    }

    public String getName(String tableName, String code) {
        TSTypegroup type = systemService.getTypeGroupByCode(tableName);
        List<TSType> tsTypes = type.getTSTypes();
        for (TSType tsType : tsTypes) {
            String typecode = tsType.getTypecode();
            if (typecode.equals(code)) {
                String typename = tsType.getTypename();
                return typename;
            }
        }
        return "";
    }
}
